package org.jeecg.modules.xl.wxbot.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecg.modules.xl.store.service.IXlCustomerStoreInfoService;
import org.jeecg.modules.xl.wxbot.entity.XlWxbotGroupMember;
import org.jeecg.modules.xl.wxbot.mapper.XlWxbotGroupMemberMapper;
import org.jeecg.modules.xl.wxbot.service.IXlWxbotGroupMemberService;
import org.jeecg.modules.xl.wxbot.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: xl_wxbot_group_member
 * @Author: jeecg-boot
 * @Date:   2025-02-12
 * @Version: V1.0
 */
@Service
public class XlWxbotGroupMemberServiceImpl extends ServiceImpl<XlWxbotGroupMemberMapper, XlWxbotGroupMember> implements IXlWxbotGroupMemberService {

    @Autowired
    private IXlCustomerStoreInfoService xlCustomerStoreInfoService;
    @Autowired
    private IXlCustomerOrdeService xlCustomerOrdeService;

    @Value("${qianxunAPiBaseURL}")
    private String qianxunAPiBaseURL;
    @Value("${botWxid}")
    private String botWxid;

    @Override
    public Result<?> sendPayWxMsm(String orderCode,Double totalRealAmount) throws InterruptedException {
        QueryWrapper<XlCustomerOrde> ordeQueryWrapper = new QueryWrapper<>();
        ordeQueryWrapper.eq("order_code",orderCode);
        XlCustomerOrde customerOrde =  xlCustomerOrdeService.getOne(ordeQueryWrapper);
        if("1".equals(customerOrde.getPaymentState())||"2".equals(customerOrde.getPaymentState())){
            return  Result.error("订单已支付，无需发起账单");
        }
        String store_code = customerOrde.getStoreCode();
        String statementurl = customerOrde.getStatementUrl();
        if(ObjectUtil.isEmpty(statementurl)){
            return  Result.error("请先上传对账单");
        }
        //查询store_code 的微信群和微信人
        QueryWrapper<XlCustomerStoreInfo> storeInfoQueryWrapper = new QueryWrapper<>();
        storeInfoQueryWrapper.eq("store_code",store_code);
        XlCustomerStoreInfo xlCustomerStoreInfo = xlCustomerStoreInfoService.getOne(storeInfoQueryWrapper);
        if(ObjectUtil.isEmpty(xlCustomerStoreInfo.getWxbotGroupWxid())||ObjectUtil.isEmpty(xlCustomerStoreInfo.getWxbotAtWxid())){
            return  Result.error("该门店未配置微信机器人，无法发起账单");
        }
        String atMems = xlCustomerStoreInfo.getWxbotAtWxid();
        StringBuilder atMemString = new StringBuilder();
        for(String  atMem : atMems.split(",")){
            String atMemTemp = "[@,wxid={},nick=,isAuto=true]";
            atMemString.append(StrUtil.format(atMemTemp,atMem));
        }
        //对账单编码
        //String statementurlUrlEncode =  URLUtil.encode(statementurlBase64);


        // 1. Base64 编码
        String statementurlBase64 = Base64.getEncoder()
                .encodeToString(statementurl.getBytes(StandardCharsets.UTF_8));
        System.out.println("Base64 编码结果: " + statementurlBase64);

        // 2. URL 编码（类似于 JavaScript 的 encodeURIComponent）
        String urlEncoded = null;
        try {
            urlEncoded = URLEncoder.encode(statementurlBase64, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
//        System.out.println("URL 编码结果: " + urlEncoded);
//
//
//        System.out.println("URL 安全的 Base64 编码结果: " + statementurl);
        String viewHost= "http://view.bugless.site:8012/onlinePreview?url=";
        //构造消息

        String template = "{}\n 尊敬的客户，您订单编号为：{}，金额为：{}元还未支付，请您尽快完成支付，以免影响下一单的配送，谢谢您的理解和支持！\n请点击查看对账单：{}";
        String msg = StrUtil.format(template,atMemString.toString(),orderCode,totalRealAmount,viewHost+urlEncoded);
        //发消息
        Map resultMap = sendTextMsg(xlCustomerStoreInfo.getWxbotGroupWxid(),msg);
        Thread.sleep(1*1000);
        sendPayCodePic(xlCustomerStoreInfo.getWxbotGroupWxid());
        if(200 == Integer.valueOf(resultMap.get("code").toString())){
            return Result.ok("账单发起成功");
        }else{
            return Result.error("发送失败，请联系管理员,原因是："+resultMap.get("msg").toString());
        }
    }

    @Override
    public Result<?> callbackapi(CallBackReq callBackReq) {
        if(!"10009".equals(callBackReq.getEvent())){
            return Result.error("不是私聊事件，直接返回");
        }
        String msg = callBackReq.getData().getData().getMsg();
        //[付款确认]-HTMflejfa-123.12
        if(!msg.contains("[付款确认]")){
            return Result.error("不是付款确认事件，直接返回");
        }
        //是付款确认
        String []  msgArra= msg.split("-");
        if(msgArra.length !=3){
            return Result.error("消息格式有误，直接返回");
        }
        String order_dode = msgArra[1];
        String real_amout = msgArra[2];
        //更新订单支付状态和订单金额
        UpdateWrapper<XlCustomerOrde> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(XlCustomerOrde::getPaymentState,1).set(XlCustomerOrde::getPaymentBy,"admin")
                        .set(XlCustomerOrde::getPaymentTime, DateUtil.now())
                .set(XlCustomerOrde::getPaymentAmount,real_amout).eq(XlCustomerOrde::getOrderCode,order_dode);
        xlCustomerOrdeService.update(updateWrapper);
        return Result.OK("回调成功");
    }

    private String buildPayMsg(String atMem, String orderCode, String payAmount){
        String template = "{},订单[{}]待支付金额：，{}元，请扫码支付";

        return StrUtil.format(template,atMem,orderCode,payAmount);
    }

    private Map sendTextMsg(String groupWxid,String msg){
        String apiUrl = qianxunAPiBaseURL+botWxid;
        QianxunBaseReq qianxunBaseReq = new QianxunBaseReq();
        qianxunBaseReq.setType("Q0001");
        Map dataMap = new HashMap();
        dataMap.put("wxid",groupWxid);//群wxid
        dataMap.put("msg",msg);//1=不获取昵称，2=获取群昵称（性能影响）
        qianxunBaseReq.setData(dataMap);
        String resultJson = HttpUtil.post(apiUrl, JSON.toJSONString(qianxunBaseReq));
        System.out.println(resultJson);
        SendMsgResp sendMsgResp = JSON.parseObject(resultJson, SendMsgResp.class);

        Map<String, Object> resultMap = MapBuilder
                .create(new HashMap<String, Object>())
                .put("code", sendMsgResp.getCode())
                .put("msg",  sendMsgResp.getMessage()).map();
        return resultMap;
    }

    private Map sendPayCodePic(String groupWxid){
        String apiUrl = qianxunAPiBaseURL+botWxid;
        QianxunBaseReq qianxunBaseReq = new QianxunBaseReq();
        qianxunBaseReq.setType("Q0010");
        Map dataMap = new HashMap();
        dataMap.put("wxid",groupWxid);//群wxid
        dataMap.put("path","D:\\HTM.jpg");
        dataMap.put("fileName","HTM收款码");
        qianxunBaseReq.setData(dataMap);
        String resultJson = HttpUtil.post(apiUrl, JSON.toJSONString(qianxunBaseReq));
        System.out.println(resultJson);
        SendMsgResp sendMsgResp = JSON.parseObject(resultJson, SendMsgResp.class);
        Map<String, Object> resultMap = MapBuilder
                .create(new HashMap<String, Object>())
                .put("code", sendMsgResp.getCode())
                .put("msg",  sendMsgResp.getMessage()).map();
        return resultMap;
    }
}
